package com.myblog.service.impl;

import com.google.common.collect.Lists;
import com.myblog.exception.BusinessException;
import com.myblog.model.po.SysPermission;
import com.myblog.model.po.SysUser;
import com.myblog.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.List;

public abstract class AbstractUserUserDetailService implements UserDetailsService {


    @Autowired
    private SysPermissionService sysPermissionService;

    public abstract SysUser findSysUser(String usernameOrMobile);


    @Override
    public UserDetails loadUserByUsername(String usernameOrMobile) throws UsernameNotFoundException {

        SysUser sysUser = findSysUser(usernameOrMobile);
        findPermission(sysUser);
        return sysUser;
    }

    private void findPermission(SysUser sysUser) {
        if (sysUser == null) {
            throw new BusinessException("用户名或密码错误");
        }
        List<SysPermission> permissions = sysPermissionService.findByUserId(sysUser.getId());
        if (CollectionUtils.isEmpty(permissions)) {
            return;
        }
        //左侧菜单渲染需要用到
        sysUser.setPermissionList(permissions);

        //封装用户权限信息
        List<GrantedAuthority> authorities = Lists.newArrayList();

        permissions.stream().forEach(permission -> {
            authorities.add(new SimpleGrantedAuthority(permission.getCode()));
        });
        sysUser.setAuthorities(authorities);
    }
}
